import Cookies from 'js-cookie';
import XEUtils from 'xe-utils';
import Watermark from '/@/utils/watermark';
import { defineStore } from 'pinia';
import { ElMessage } from 'element-plus';

import { Session } from '@/utils';
import { AuthUtils } from '@/utils/auth';
import { useLoginApi, useSystemApi } from '@/api';
import { LocalStorage } from '/@/utils/storage';
import { useThemeConfig } from '/@/stores/themeConfig';
// 其他的store
import { useUserStore, useUserInfo } from '@/stores/modules/store-user';
// const storesThemeConfig = useThemeConfig();
// const { themeConfig } = storeToRefs(storesThemeConfig);
// // 获取布局配置信息
// const getThemeConfig = computed(() => {
// 	return themeConfig.value;
// });

const defaultSysParams = {
	// 系统名称
	sysName: '',
	// 系统简称
	sysShortName: '',
	// 等保级别：1-等保一级 2-等保二级 3-等保三级 4-等保四级
	protectLevel: 4,
	// 系统签名
	sysCopyright: 'Copyright 2016 北京大数元科技发展有限公司 版权所有 All rights reserved.',
	// 备案信息
	filingContent: '',
};

/**
 * 处理登录的通用方法
 */
export const useSystemStore = defineStore('system', {
	state: () => ({
		// 权限token
		token: AuthUtils.accessToken.get(),
		// 系统模式：['custom', 'develop', 'development', 'production', 'ad34', 'ad35']
		envMode: import.meta.env.MODE,
		// 系统参数
		systemParams: XEUtils.clone(defaultSysParams, true),
		// 外部系统调用配置
		extCallConfig: {
			isCall: false,
			isMenu: false,
			callToken: '',
			systemName: import.meta.env.VITE_EXTERNAL_CALL_SYS_NAME || '',
			logoutPath: import.meta.env.VITE_EXTERNAL_CALL_LOGIN_PATH || '',
		},
		// 是否开启请求服务器
		openRequestServer: true,
		// 特殊独立添加水印的路径
		warterMarkPaths: [
			// 专家在线评审模块
			'/review/expert-online-review'
		],
	}),
	actions: {
		/**
		 * 退出登录方法
		 * @param {Boolean} apiTimeout 是否为Api超时跳出
		 * @returns Promise
		 */
		signOut(apiTimeout = false) {
			return new Promise((resolve, reject) => {
				if (this.openRequestServer) {
					useLoginApi().logout().then((res) => {
						this.setExtCallConfig();
						this.clearAllCache();
						this.jumpToLoginPage(apiTimeout);
						resolve(true);
					}).catch((err) => {
						this.clearAllCache();
						reject(err);
					});
				} else {
					this.clearAllCache();
					this.jumpToLoginPage();
					resolve(true);
				}
			});
		},
		// SSO登录
		signInSSO(params) {
			return new Promise((resolve, reject) => {
				this.clearAllCache();
				useLoginApi().ssoLogin(params).then((res) => {
					const { code, data, msg } = res;
					const result = {
						flag: false,
						message: msg
					}
					if (code == 200) {
						const { Authorization } = data;
						this.token = Authorization;
						AuthUtils.accessToken.set(Authorization);
						result.flag = true
					} else {
						this.token = '';
						AuthUtils.accessToken.remove();
						// ElMessage.error(msg);
						result.flag = false
					}
					resolve(result)
				})
					.catch((err) => {
						this.token = '';
						AuthUtils.accessToken.remove();
						console.error(err);
						resolve({
							flag: false,
							result: {
								msg: err
							}
						});
					});
			});
		},
		// 后端登录
		signInBack(params) {
			return new Promise((resolve, reject) => {
				useLoginApi()
					.login(params)
					.then((res) => {
						const { code, data, msg } = res;
						if (code == 200) {
							const { Authorization } = data;
							this.token = Authorization;
							AuthUtils.accessToken.set(Authorization);
							resolve(true);
						} else {
							this.token = '';
							AuthUtils.accessToken.remove();
							ElMessage.error(msg);
							resolve(false);
						}
					})
					.catch((err) => {
						this.token = '';
						AuthUtils.accessToken.remove();
						console.error(err);
						resolve(false);
					});
			});
		},
		// 前端登录
		signInFront(params) {
			return new Promise((resolve, reject) => {
				// 前端登录生产token
				const token = Math.random().toString(36).substring(0);
				this.token = token;
				// 缓存token，用于前端路由跳转时做登录判断
				AuthUtils.accessToken.set(token);
				// 模拟数据，对接接口时，记得删除多余代码及对应依赖的引入。用于 `/src/stores/userInfo.ts` 中不同用户登录判断（模拟数据）
				Cookies.set('userName', params?.userName || 'admin');
				// 返回参数信息
				resolve(true);
			});
		},
		// 手机号登录
		signInMobile(params) {
			return new Promise((resolve, reject) => {
				useLoginApi()
					.mobileLogin(params)
					.then((res) => {
						const { code, data, msg } = res;
						if (code == 200) {
							const { Authorization } = data;
							this.token = Authorization;
							AuthUtils.accessToken.set(Authorization);
							resolve(true);
						} else {
							this.token = '';
							AuthUtils.accessToken.remove();
							ElMessage.error(msg);
							resolve(false);
						}
					})
					.catch((err) => {
						this.token = '';
						AuthUtils.accessToken.remove();
						console.error(err);
						resolve(false);
					});
			});
		},
		/**
		 * 系统外部调用
		 * @param {Object} params 参数
		 */
		signInExtCall(params) {
			let { token, itoken, userid, isMenu } = params
			// 处理参数
			const callKey = LocalStorage.get('relate_call_key')
			// 相同的用户
			const sameUser = (callKey == userid)
			if (userid && !sameUser) {
				console.info('diff user, will clear cache')
				this.clearAllCache(false);
			}
			// 调用的Token
			const callToken = token || (itoken ? atob(itoken) : '')
			// 外调信息
			const extCallInfo = {
				isCall: true,
				isMenu: isMenu || false,
				callToken
			}
			// 最终结果
			const finalResult = {
				flag: false, message: '',
				existAccessToken: false
			}
			return new Promise(async (resolve) => {
				// 存在认证token
				if (AuthUtils.accessToken.check()) {
					finalResult.flag = true
					finalResult.message = 'In ExtCall Login Success For Exist Assess Token'
					finalResult.existAccessToken = true
				} else {
					// 清除缓存
					this.clearAllCache(false);
					// 筹划评审调用，无需调用sso登录
					if (itoken) {
						this.token = callToken
						AuthUtils.accessToken.set(callToken)
						finalResult.flag = true
						finalResult.message = 'In ExtCall Login Success For Itoken'
					} else {
						try {
							const res = await useLoginApi().ssoLogin({ accessToken: token })
							const { code, data, msg } = res;
							if (code === 200) {
								const { Authorization } = data
								this.token = Authorization
								AuthUtils.accessToken.set(Authorization)
								finalResult.flag = true
								finalResult.message = 'In ExtCall Login Success For ssoLogin'
							} else {
								this.token = ''
								AuthUtils.accessToken.remove()
								finalResult.flag = false
								finalResult.message = msg
								console.error('In ExtCall Login Failed', msg);
							}
						} catch(error) {
							this.token = ''
							AuthUtils.accessToken.remove()
							finalResult.flag = false
							finalResult.message = error
							console.error('In ExtCall Login Failed', error);
						}
					}
				}
				if (finalResult.flag) {
					LocalStorage.set('ext_call_info', extCallInfo)
					LocalStorage.set('relate_call_key', userid)
					this.setExtCallConfig(extCallInfo)
				}
				resolve(finalResult)
			})
		},
		// 情况所有缓存
		clearAllCache(clearCookies = true) {
			this.token = '';
			if (this.openRequestServer) {
				useUserInfo().clearUserInfo();
				useUserStore().clearUser();
			}
			// 系统参数
			this.systemParams = XEUtils.clone(defaultSysParams, true);
			
			// localStorage的一些数据不清除
			Object.keys(localStorage).forEach((key) => {
				// 清空浏览器缓存排除了主题设置
				if (!(key.includes('themeConfig') || key.startsWith('score:'))) {
					localStorage.removeItem(key);
				}
				// 排除评估中心暂存时间scoreTime
				if (!(key.includes('themeConfig') || key.startsWith('scoreTime:'))) {
					localStorage.removeItem(key);
				}
			});

			//排除评估中心修改标志
			Object.keys(sessionStorage).forEach((key) => {
				if (!(key.includes('themeConfig') || key.startsWith('scorewrite:'))) {
					sessionStorage.removeItem(key);
				}
			});
			// // 是否清除Cookies
			// if (clearCookies) {
			// 	Object.keys(Cookies.get()).forEach((key) => { Cookies.remove(key) });
			// }
		},
		// 清除缓存
		clearSignInCache() {
			this.token = '';
			Session.clear();
			AuthUtils.accessToken.remove();
		},
		/**
		 * 跳转登录页面
		 * @param {Boolean} apiTimeout 是否为Api超时跳出
		 */
		jumpToLoginPage(apiTimeout) {
			let extCallInfo = LocalStorage.get('ext_call_info')
			if (extCallInfo) {
				extCallInfo = { ...this.extCallConfig, ...extCallInfo }
			} else {
				extCallInfo = this.extCallConfig
			}
			const { loginUrlRedirect } = this.systemParams
			const { isCall, logoutPath } = extCallInfo
			let finalLogoutPath = loginUrlRedirect || logoutPath
			if (isCall) {
				if (finalLogoutPath) { window.location.href = finalLogoutPath; }
			} else {
				if (apiTimeout) {
					sessionStorage.setItem('timeout', Math.random().toString(36).substring(0))
				}
				location.reload(false);
			}
		},
		//界面显示 --> 开启水印
		changeWarterMark(isexpert) {
			//如果是专家评审模块 
			if (isexpert == true) {
				const userCode = useUserStore().userInfo.userCode;
				const userName = useUserStore().userInfo.userName;
				Watermark.set(userCode +" "+ userName)
			} else {
				useThemeConfig().themeConfig.isWartermark ? Watermark.set(useThemeConfig().themeConfig.wartermarkText) : Watermark.del();
			}
		},
		// 设置系统参数
		setSystemParams() {
			return new Promise((resolve) => {
				if (this.openRequestServer) {
					useSystemApi()
						.getSysParams()
						.then((res) => {
							const { code, data, msg } = res;
							if (code === 200) {
								this.systemParams = { ...this.systemParams, ...data };
								const { sysIsGrayscale, sysIsPageWatermark, sysIsFooter, sysFrameLogoName } = data;
								// 开启底部栏
								useThemeConfig().themeConfig.isFooter = sysIsFooter && Number(sysIsFooter) === 1;
								// 灰色模式
								useThemeConfig().themeConfig.isGrayscale = sysIsGrayscale && Number(sysIsGrayscale) === 1;
								// 是否水印
								useThemeConfig().themeConfig.isWartermark = sysIsPageWatermark && Number(sysIsPageWatermark) === 1;
								if (sysFrameLogoName) {
									// 全局网站名称
									useThemeConfig().themeConfig.globalTitle = sysFrameLogoName;
									// 水印文案
									useThemeConfig().themeConfig.wartermarkText = sysFrameLogoName;
									// 全局副标题
									useThemeConfig().themeConfig.globalViceTitle = sysFrameLogoName;
								}
								this.sysIsPageWatermark = sysIsPageWatermark
								this.sysFrameLogoName = sysFrameLogoName
							} else {
								console.error('err', msg);
							}
						})
						.catch((err) => {
							console.error('err', err);
						});
				} else {
					// 前端控制路由 不做任何操作
				}
			});
		},
		// 设置外部调用配置
		setExtCallConfig(config = {}) {
			let extCallInfo = LocalStorage.get('ext_call_info') || {}
			this.extCallConfig = { ...this.extCallConfig, ...config, ...extCallInfo };
			return this.extCallConfig
		},
	},
});
